package com.ymh.git.thread.juc.goods;

import com.ymh.git.thread.juc.SleepTools;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by aivin on 2018/11/6.
 */
public class UseRwLock implements GoodsService {


    private GoodsInfo goodsInfo;

    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    private final Lock readLock = lock.readLock();// 读锁
    private final Lock writeLock = lock.writeLock();// 写锁

    public UseRwLock(GoodsInfo goodsInfo) {
        this.goodsInfo = goodsInfo;
    }

    @Override
    public GoodsInfo getNum() {
        readLock.lock();
        try {
            SleepTools.ms(5);
            return this.goodsInfo;
        } finally {
            readLock.unlock();
        }
    }

    @Override
    public void setNum(int num) {
        writeLock.lock();
        try {
            SleepTools.ms(5);
            goodsInfo.changeNumber(num);
        } finally {
            writeLock.unlock();
        }


    }
}
